<?php

namespace App\Admin\Controllers;

use App\Miya\Models\MsgForm;
use App\Miya\Models\MsgFormField;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;

class MsgFormController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '询盘表单设置';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new MsgForm());
        $grid->model()->with(['fields']);

        $grid->column('id', '序号');
        $grid->column('name', '表单名')->label();
        $grid->column('fields', '字段')->display(function () {
            return $this->fields->count();
        })->modal('字段', function ($model) {
            $data = $model->fields->map(function ($field) {
                $data = $field->only(['id', 'name', 'field', 'is_required', 'values']);
                $data['is_required'] = $data['is_required'] == 1 ? '必填' : '选填';
                return $data;
            })->toArray();

            return new Table(['序号', '字段', '字段名', '是否必填?', '可选值'], $data);
        });

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new MsgForm());

        $form->tab('基础设置', function (Form $form) {
            $form->text('name', '表单名称')->rules(['required']);
            $form->hasMany('fields', '字段', function (Form\NestedForm $form) {
                $form->text('name', '字段名')->rules(['required']);
                $form->text('field', '字段')->rules(['required']);
                $form->radio('is_required', '是否必填?')
                    ->default(1)->options([1 => '必填', 2 => '选填']);
                $form->tags('values', '可选值');
            });
        })->tab('高级设置', function (Form $form) {
            $form->text('response_hint', '提示语')->rules(['required'])->default('询盘信息提交成功!');
        });

        return $form;
    }
}
